import { Component, OnInit, ChangeDetectorRef, ViewChild, Inject, Output, forwardRef, EventEmitter } from '@angular/core';
import { AppComponent } from '../../../../app.component';
import { path } from '../../../../path.config';
import { masterService } from '../../../../../lib/master.service';
import { NzModalService } from 'ng-zorro-antd';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { ResultComponent } from './result/result.component';

@Component({
    selector: 'voucher-batch-to-user',
    templateUrl: './grid.component.html',
    styleUrls: ['./grid.component.css'],
    providers: [forwardRef(() => AppComponent)]
})
export class GridComponent implements OnInit {
    @ViewChild('pvModal') pvModal: ModalDirective;
    @ViewChild('resultForm') resultForm: ResultComponent;

    @Output() removeVoucher = new EventEmitter<any>();

    // 列表API
    public getList: any = path.voucherManage.voucherBatch.getList;
    // 列表详情API
    public getItemList: any = path.voucherManage.voucherBatch.getItemList;
    // 取消优惠券
    private removeBatch = path.voucherManage.voucherBatch.removeBatch;

    public rows: Array<any> = [];

    // 表格数据头部标题
    public columns: Array<any> = [
        { title: '创建时间', name: 'createdTime' },
        { title: '模板编号', name: 'templateId' },
        { title: '模板名称', name: 'templateName' },
        { title: '操作人', name: 'createdBy' },
        { title: '执行状态', name: 'status' },
        { title: '执行结果', name: 'resultNote' },
        { title: '操作', name: 'btn' }
    ];
    // 当前页码
    public page: any = 1;
    // 一共多少页
    public itemsPerPage: number = 10;
    // 分页最多显示的页数
    public maxSize: number = 5;
    // 总页数计数变化时，事件数等于总页数计数
    public numPages: number = 1;
    // 总共的列表项数
    public totalItems: number = 0;
    // 分页器的文本配置
    public localText = {
        firstBtn: '首页',
        lastBtn: '末页',
        previousBtn: '上一页',
        nextBtn: '下一页'
    }

    public filter: any = {
        pageSize: '10',
        pageIndex: '1'
    }
    constructor(public _masterService: masterService,
        public cdRef: ChangeDetectorRef,
        private confirmServ: NzModalService,
        @Inject(forwardRef(() => AppComponent)) private app: AppComponent) { }

    public ngOnInit() {
        this.onChangeTable();
    }

    // 渲染表格
    public onChangeTable = (urlObj?) => {
        if (urlObj) {
            this.filter.pageSize = urlObj.itemsPerPage;
            this.filter.pageIndex = urlObj.page;
        }
        this._masterService
            .getData(this.getList, this.filter)
            .subscribe((res) => {
                if (res.statusCode == 200) {
                    this.rows = res.data.items;
                    this.totalItems = res.data.pagination.totalCount;
                    this.itemsPerPage = res.data.pagination.pageSize;
                    this.page = parseInt(res.data.pagination.pageIndex);
                    this.cdRef.detectChanges();
                } else if (res.statusCode == 401) {
                    this.app.logOff();
                } else {
                    this.app.toastError('错误信息： ' + res.errorMessage);
                }
            })
    }

    // 打开结果弹窗
    public openResultModal(rowId) {
        this.resultForm.item.rowId = rowId;
        this.resultForm.onChangeTable(null, rowId);
        this.pvModal.show();
    }

    public closeModal() {
        this.resultForm.item.rowId = 0;
        this.pvModal.hide();
    }

    cancelVoucher (id: number):void {
        let removeBatch = (id) => {
            this._masterService
                .getData(this.removeBatch, {id: id})
                .subscribe(res => {
                    if (res.statusCode === "200") {
                        if (res.data.count === 0) {
                            if (res.errroMessage) {
                                this.app.toastError('错误信息：' + res.errroMessage)
                            } else {
                                this.app.toastWarning('正在执行中')
                            }
                        } else if (res.data.count > 0) {
                            this.app.toastSuccess('取消成功！')
                            this.removeVoucher.emit()
                        }
                    }
                })
        }

        this.confirmServ.confirm({
            nzTitle: '是否确认取消？',
            nzOnOk() {
                removeBatch(id)
            }
        })
    }
}
